package com.yy.micro.magic.ext.domain.filter;

import com.fasterxml.jackson.annotation.JsonIgnore;

import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Pattern;

public class DynamicTrigger {
    private String planCode;
    private String trigger;
    private String[] patterns;

    public String getPlanCode() {
        return planCode;
    }

    public void setPlanCode(final String planCode) {
        this.planCode = planCode;
    }

    public String getTrigger() {
        return trigger;
    }

    public void setTrigger(final String trigger) {
        this.trigger = trigger;
    }

    public String[] getPatterns() {
        return patterns;
    }

    public void setPatterns(final String[] patterns) {
        this.patterns = patterns;
    }

    public static DynamicTrigger create(String planCode, String trigger, String[] patterns){
        Assert.notNull(planCode,"planCode not empty.");
        Assert.notNull(trigger,"trigger not empty.");
        Assert.notNull(patterns,"pattern not empty.");
        DynamicTrigger fc = new DynamicTrigger();
        fc.planCode=planCode;
        fc.trigger = trigger;
        fc.patterns = patterns;
        return fc;
    }

    @JsonIgnore
    public boolean match(String planCode,String trigger){
        Assert.notNull(planCode,"planCode not empty.");
        Assert.notNull(trigger,"trigger not empty.");
        if (this.planCode.equals(planCode) && Pattern.matches(this.trigger,trigger)){
            return true;
        }
        return false;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final DynamicTrigger that = (DynamicTrigger) o;
        return planCode.equals(that.planCode) && trigger.equals(that.trigger) && Arrays.equals(patterns, that.patterns);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(planCode, trigger);
        result = 31 * result + Arrays.hashCode(patterns);
        return result;
    }
}
